#pragma once
//会话信息的新增/删除/获取
//登录状态的新增/删除/判断是否查找 用户ID和空值的键值对
//验证码的新增/删除/获取

#include <sw/redis++/redis++.h>
#include <iostream>
#include <memory>

namespace zrb
{
    class RedisClientFactory
    {
    public:
        static std::shared_ptr<sw::redis::Redis> create(
            const std::string& ip,
            int32_t port,
            int32_t db,
            bool keep_alive)
        {
            //1. 构造连接选项，实例化Redis对象，连接服务器
            sw::redis::ConnectionOptions opts;
            opts.host = ip;
            opts.port = port;
            opts.db = db;
            opts.keep_alive = keep_alive;
            return std::make_shared<sw::redis::Redis>(opts);
        }
    };

    class Session
    {
    public:
        using ptr = std::shared_ptr<Session>;
        Session(const std::shared_ptr<sw::redis::Redis>& RedisClient)
            :_RedisClient(RedisClient)
        {}

        //会话id和用户id 添加会话
        void append(const std::string& ssid,const std::string& uid)
        {
            _RedisClient->set(ssid,uid);
        }

        //删除会话
        void remove(const std::string& ssid)
        {
            _RedisClient->del(ssid);
        }

        //获取会话id
        sw::redis::OptionalString uid(const std::string& ssid)
        {
            return _RedisClient->get(ssid);
        }

    private:
        std::shared_ptr<sw::redis::Redis> _RedisClient;
    };

    //用户登陆状态
    class Status
    {
    public:
        using ptr = std::shared_ptr<Status>;
        Status(const std::shared_ptr<sw::redis::Redis>& RedisClient)
            :_RedisClient(RedisClient)
        {}

        //用户id 
        void append(const std::string& ssid)
        {
            _RedisClient->set(ssid,""); //value设置为空就可以，目的是key存在，证明该用户已经登录
        }

        //删除
        void remove(const std::string& ssid)
        {
            _RedisClient->del(ssid);
        }

        //获取
        bool exist(const std::string& ssid)
        {
            auto res = _RedisClient->get(ssid);
            if(res)
                return true;

            return false;
        }

    private:
        std::shared_ptr<sw::redis::Redis> _RedisClient;
    };

    //验证码
    class Code
    {
    public:
        using ptr = std::shared_ptr<Code>;
        Code(const std::shared_ptr<sw::redis::Redis>& RedisClient)
            :_RedisClient(RedisClient)
        {}

        //添加验证码 验证码id和验证码
        void append(const std::string& cid,const std::string& code)
        {
            _RedisClient->set(cid,code,std::chrono::seconds(180)); //180秒，即3分钟
        }

        //删除验证码
        void remove(const std::string& cid)
        {
            _RedisClient->del(cid);
        }

        //获取验证码
        sw::redis::OptionalString uid(const std::string& cid)
        {
            return _RedisClient->get(cid);
        }

    private:
        std::shared_ptr<sw::redis::Redis> _RedisClient;
    };
}